package com.buli.minio.controller;


import com.buli.minio.service.FileService;
import io.minio.errors.MinioException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

import static com.fasterxml.jackson.databind.type.LogicalType.Map;

@RestController
@RequestMapping("/api/files")
public class FileController {

    @Autowired
    private FileService fileService;


    /**
     * 单个文件上传
     *
     * @param file 上传的文件
     * @return 文件 URL
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws MinioException
     */
    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> uploadSingleFile(@RequestParam("file") MultipartFile file) {
        try {
            String fileUrl = fileService.uploadSingleFile(file);
            Map<String, Object> response = new HashMap<>();
            response.put("status", "success");
            response.put("url", fileUrl);
            return ResponseEntity.ok(response); // 自动转为 JSON
        } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | MinioException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", "error");
            errorResponse.put("message", "文件上传失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }


    /**
     * 批量文件上传
     *
     * @param files 上传的文件列表
     * @return 文件 URL 列表
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws MinioException
     */
    @PostMapping("/upload-multiple")
    public ResponseEntity<List<String>> uploadMultipleFiles(@RequestParam("files") List<MultipartFile> files) {
        try {
            List<String> fileUrls = fileService.uploadMultipleFiles(files);
            return ResponseEntity.ok(fileUrls);
        } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | MinioException e) {
            return ResponseEntity.status(500).body(Collections.singletonList("文件上传失败: " + e.getMessage()));
        }
    }

    /**
     * 单个文件下载
     *
     * @param fileName 文件名
     * @return 文件 URL
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws MinioException
     */
    @GetMapping("/download/{fileName}")
    public ResponseEntity<String> downloadSingleFile(@PathVariable("fileName") String fileName) {
        try {
            String fileUrl = fileService.downloadSingleFile(fileName);
            return ResponseEntity.ok(fileUrl);
        } catch (NoSuchElementException e) {
            return ResponseEntity.status(404).body("文件未找到: " + e.getMessage());
        } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | MinioException e) {
            return ResponseEntity.status(500).body("文件下载失败: " + e.getMessage());
        }
    }

    /**
     * 批量文件下载为 ZIP 压缩包
     *
     * @param fileNames 文件名列表
     * @return ZIP 文件的 URL
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws MinioException
     */
    @GetMapping("/download-zip")
    public ResponseEntity<String> downloadMultipleFilesAsZip(@RequestParam("fileNames") List<String> fileNames) {
        try {
            String zipFileUrl = fileService.downloadMultipleFilesAsZip(fileNames);
            return ResponseEntity.ok(zipFileUrl);
        } catch (NoSuchElementException e) {
            return ResponseEntity.status(404).body("文件未找到: " + e.getMessage());
        } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | MinioException e) {
            return ResponseEntity.status(500).body("文件下载失败: " + e.getMessage());
        }
    }

    /**
     * 获取图片预览URL
     *
     * @param objectName 文件对象名
     * @return 预览 URL
     */
    @GetMapping("/preview/image/{objectName}")
    public ResponseEntity<Map<String, Object>> getImagePreviewUrl(@PathVariable("objectName") String objectName) {
        try {
            String previewUrl = fileService.getImagePreviewUrl(objectName);
            Map<String, Object> response = new HashMap<>();
            response.put("status", "success");
            response.put("previewUrl", previewUrl);
            response.put("type", "image");
            return ResponseEntity.ok(response);
        } catch (NoSuchElementException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", "error");
            errorResponse.put("message", "文件未找到: " + e.getMessage());
            return ResponseEntity.status(404).body(errorResponse);
        } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | MinioException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", "error");
            errorResponse.put("message", "获取预览URL失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 获取文件预览URL（支持多种文件类型）
     *
     * @param objectName 文件对象名
     * @return 预览 URL
     */
    @GetMapping("/preview/file/{objectName}")
    public ResponseEntity<Map<String, Object>> getFilePreviewUrl(@PathVariable("objectName") String objectName) {
        try {
            String previewUrl = fileService.getFilePreviewUrl(objectName);
            Map<String, Object> fileInfo = fileService.getFileInfo(objectName);
            
            Map<String, Object> response = new HashMap<>();
            response.put("status", "success");
            response.put("previewUrl", previewUrl);
            response.put("fileInfo", fileInfo);
            return ResponseEntity.ok(response);
        } catch (NoSuchElementException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", "error");
            errorResponse.put("message", "文件未找到: " + e.getMessage());
            return ResponseEntity.status(404).body(errorResponse);
        } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | MinioException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", "error");
            errorResponse.put("message", "获取预览URL失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 获取文件信息
     *
     * @param objectName 文件对象名
     * @return 文件信息
     */
    @GetMapping("/info/{objectName}")
    public ResponseEntity<Map<String, Object>> getFileInfo(@PathVariable("objectName") String objectName) {
        try {
            Map<String, Object> fileInfo = fileService.getFileInfo(objectName);
            Map<String, Object> response = new HashMap<>();
            response.put("status", "success");
            response.put("fileInfo", fileInfo);
            return ResponseEntity.ok(response);
        } catch (NoSuchElementException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", "error");
            errorResponse.put("message", "文件未找到: " + e.getMessage());
            return ResponseEntity.status(404).body(errorResponse);
        } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | MinioException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", "error");
            errorResponse.put("message", "获取文件信息失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 检查文件是否支持预览
     *
     * @param objectName 文件对象名
     * @return 预览支持信息
     */
    @GetMapping("/preview/check/{objectName}")
    public ResponseEntity<Map<String, Object>> checkPreviewSupport(@PathVariable("objectName") String objectName) {
        try {
            Map<String, Object> fileInfo = fileService.getFileInfo(objectName);
            Map<String, Object> response = new HashMap<>();
            response.put("status", "success");
            response.put("canPreview", fileInfo.get("canPreview"));
            response.put("fileType", getFileTypeDescription(fileInfo));
            response.put("fileInfo", fileInfo);
            return ResponseEntity.ok(response);
        } catch (NoSuchElementException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", "error");
            errorResponse.put("message", "文件未找到: " + e.getMessage());
            return ResponseEntity.status(404).body(errorResponse);
        } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | MinioException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", "error");
            errorResponse.put("message", "检查预览支持失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 获取文件类型描述
     */
    private String getFileTypeDescription(Map<String, Object> fileInfo) {
        if ((Boolean) fileInfo.get("isImage")) {
            return "图片文件";
        } else if ((Boolean) fileInfo.get("isVideo")) {
            return "视频文件";
        } else if ((Boolean) fileInfo.get("isDocument")) {
            return "文档文件";
        } else {
            return "其他文件";
        }
    }
}
